﻿using System.Linq;
using Dogshow.BusinessLogic.Utils;
using Dogshow.Infrastructure.Exceptions;
using Dogshow.Model;
using DogshowRepository;

namespace Dogshow.BusinessLogic.Services.Impl
{
    public class PrijavaManager
    {
        private readonly IKorisniciRepository m_KorisniciRepository;

        private readonly IEncryptor m_Encryptor;

        public PrijavaManager(IKorisniciRepository korisniciRepository, IEncryptor encryptor)
        {
            m_KorisniciRepository = korisniciRepository;
            m_Encryptor = encryptor;
        }

        public Korisnik PrijaviKorisnika(string username, string password)
        {
            var korisnik = m_KorisniciRepository.VratiPoKorisnickomImenu(username);

            if (korisnik == null)
            {
                throw new LoginException("Korisničko ime nije registrovano");
            }

            if (!korisnik.Aktivan)
            {
                throw new LoginException("Vaš korisnički nalog je zaključan. Obratite se administratoru");
            }

            var encryptedPass = m_Encryptor.Encrypt(password);

            if (!korisnik.Lozinka.SequenceEqual(encryptedPass))
            {
                throw new LoginException("Lozinka se ne poklapa");
            }

            return korisnik;
        }
    }
}